package com.yhs.YShop.config;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

//@Order(1)
//@Component
//@WebFilter(filterName = "myWebFilter", urlPatterns = { "/*" })
public class MyWebFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
        System.err.println("过滤器------------");
		// 设置允许跨域访问
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "*");
		response.setHeader("Access-Control-Max-Age", "3600");
		// response.setHeader("Access-Control-Allow-Headers", "*");
		response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Authorization,"
				+ " Content-Type, Accept, Connection, User-Agent, Cookie,token");

		// OPTIONS请求直接放行
		if ("OPTIONS".equals(request.getMethod())) {
			chain.doFilter(request, response);
			return;
		}

		// 权限校验
		if (!checkAuthority()) {
			writeFailure(response);
			return;
		}

		chain.doFilter(request, response);
	}

	public void destroy() {
	}

	/** 权限校验 */
	private boolean checkAuthority() {
		// TODO 这里进行权限检查

		return true;
	}

	/** 校验失败返回 */
	private void writeFailure(HttpServletResponse response) {
		// 让浏览器用utf8来解析返回的数据
		response.setHeader("Content-type", "application/json;charset=UTF-8");
		// 告诉servlet用UTF-8转码，而不是用默认的ISO8859
		response.setCharacterEncoding("UTF-8");
//		JSONObject result = new JSONObject();
//		result.put("status", "error");
//		result.put("message", "对不起，你没有权限!");
		String result = "对不起，你没有权限!";
		PrintWriter writer;
		try {
			writer = response.getWriter();
			writer.write(result);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
